package com.hunan.api.catv.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

public class FileUtils {
    public static Logger log = LoggerFactory.getLogger(FileUtils.class);

    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }

    public static String getMd5ByFile(File file) {
        String value = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = String.format("%032x", bi);
        } catch (Exception e) {
            log.error("FileUtils Error:{} ", e);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("FileUtils Error:{} ", e);
                }
            }
        }
        return value;
    }

    public static String convertVideoDuration(String duration) {
        duration = duration.substring(0, duration.lastIndexOf("."));
        long seconds = Long.valueOf(duration);
        long min = 60;
        long hour = 60 * 60;
        if (seconds >= min && seconds < hour) {
            return seconds / min + " 分钟 " + seconds % min + " 秒";
        }
        if (seconds >= hour) {
            return seconds / hour + " 小时 " + (seconds - hour) / min + " 分钟 " + seconds % min + " 秒";
        }
        return seconds + " 秒";
    }
}
